package com.frxuexi.park

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.base.entity.ParkBean
import com.frxuexi.base.entity.ParkBeanItem
import com.frxuexi.base.entity.Res
import com.frxuexi.base.http.ApiService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext

class ParkDataSource(val apiService: ApiService,val para:String,val which:String):PagingSource<Int,ParkBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, ParkBeanItem>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ParkBeanItem> {
        return withContext(Dispatchers.IO){
            try {
                var res:Res<ParkBean>?=null
                var res2:Res<ParkBeanItem>?=null
                val list = mutableListOf<ParkBeanItem>()
                if(which=="类型") {
                    res = apiService.getParkByType(para).first()
                    list.addAll(res.data)
                }else if(which=="状态"){
                    res = apiService.getParkByStatus(para).first()
                    list.addAll(res.data)
                }else if(which=="区域"){
                    res = apiService.getParkByArea(para.toInt()).first()
                    list.addAll(res.data)
                }else if(which=="用户"){
                    res2 = apiService.getParkByUid(para.toInt()).first()
                    list.add(res2.data)
                }else if(which=="车牌号"){
                    res2 = apiService.getParkByCarNo(para).first()
                    list.add(res2.data)
                }
                if(res!!.code==200 || res2!!.code==200) {
                    LoadResult.Page(list.sortedByDescending { it.id }, null, null)
                }else{
                    LoadResult.Error(Exception(res?.message?:res2?.message))
                }
            }catch (e:Exception){
                LoadResult.Error(e)
            }
        }
    }
}